<template>
	<view class="uploadQualification">

		<!-- 实例 https://ext.dcloud.net.cn/plugin?id=63 -->

		<view>
			<view class="htitle">
				上传健康证
			</view>
			<view class="text">
				上传本人<text style="color:#1E6CEB">有效期内健康证彩色高清实拍</text>照片
			</view>

			<sunui-upimg1  :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode" :header="header"
				:size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl" ref="selectimgandupload1"
				@uploaded="imgLoaded1" @change="imgsChange1" :maxFileNumber="9"><template v-slot:icon>
								<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
							</template></sunui-upimg1>
	
		</view>
		<view class="sumbit-btn flex" @click.stop="uploadHealthCertificateFn()">
			点击上传
		</view>
	</view>
</template>
<script>
	import {
		mapMutations
	} from 'vuex'
	import {
		mapState
	} from 'vuex'
	import {
		mapGetters
	} from 'vuex'
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		data() {
			return {
				img: [],
				// 上传资格证
				form: {
					healthCertificate: '',
				},

				storageMode: '',
				photos: 'http://tmp/oPvxqRtPPstDa128a34f30dbb644483d8ec6e94e75c9.jpg',
				upPicUrl: '',
				imgFormData: null,
				alyOssSignatureInfo: null,
				header: null,
				timeDate: '',
				suffix: '',
				// 上传图片的数组
				uploaderArr: [],
				imgViewArr: [],
				imgStr:[],
				file:[],
				technicianDetail:{}
			}
		},
		computed: {

			...mapGetters('user', ['taskCenter', 'technicianDetails']),

		},
		onLoad() {
			this.getUploadConfig(),
				this.init()
		},
		methods: {


			...mapMutations('user', ['uploadHealthCertificate', 'uploadProgress','technicianDetailsFn']),
			init() {
				if (this.technicianDetails.authenticationNot == 3) {
					this.$sun.assignObject(this.form, {
						...this.technicianDetails
					})
					console.log(this.form)
					console.log(this.form.healthCertificate)
					const imgStr = this.form.healthCertificate
					if (imgStr.length) {
						if (imgStr.includes(',')) {
							console.log('字符串中包含逗号');
							// 包含的进行slice(',') 分割

							this.imgStr = imgStr.split(',').map((item) => item.trim());
							console.log(this.imgStr)
							this.$refs.selectimgandupload1.setItems(this.imgStr);
						} else {
							console.log('字符串中不包含逗号');
							this.imgStr = imgStr.split();
							this.$refs.selectimgandupload1.setItems(this.imgStr);
						}

						this.viewerVisible = true;
					}

				}
			},
			async getUploadConfig() {
				const result = await this.$http.get({
					url: this.$api.getStorageConfig,
					data: {}
				});
				if (result.code == 200) {
					this.storageMode = result.data.storageMode; // storageMode:2是‘阿里云’上传，3是‘七牛云’ 上传
					console.log('this.storageMode', this.storageMode);

				} else {
					console.log('result.message', result.message);
				}
			},



			// “上传图片”发生改变
			imgsChange1(file) {
				// 文件名
				this.timeDate = new Date().getTime();
				console.log('上传发生改变this.storageMode1111============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (this.storageMode == 2) {
					this.userOssSignature(file);
				}
				if (this.storageMode == 3) {
					this.upPicUrl = this.$api.qnyOssSignature;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				}
			},
			// 阿里云上传
			async userOssSignature(file) {
				
				console.log('this阿里云上传进入=======');
				const ts = new Date().getTime();
				const us = {
					ts
				};
				let url = this.$api.alyOssSignature + `${object2Url(us)}`;
				const res = await this.$http.get({
					url: url,
					data: {
						us: us
					}
				});
				this.ossInfo = res.data;
				this.upPicUrl = this.ossInfo?.host;
				// 获取上传图片名称和后缀
				console.log( file)
			
				if(file.length){
					let fileUrl = file[0].url;
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀
					
					console.log('this.ossInfo', this.ossInfo);
					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
					console.log('页面阿里云url22222222222222', this.ossInfo?.host + '/' + this.timeDate + this.suffix);
				}else{
					this.imgStr=[]
				}
			
			},

			// 上传图片返回
			imgLoaded1(e) {
				console.log('上传返回eeeee222============', e);
				try {
					this.img = [];
					for (let i = 0; i < e.length; i++) {
						this.img.push(e[i].url);
					}
				} catch (e) {
					this.img = [];
				}
				console.log('this.img=======', this.img);
				this.imgStr = this.img
				console.log(this.imgStr)
				this.form.healthCertificate = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr.join(',');
			},
			// handleLoaded1(e) {
			// 	console.log(e);

			// 	if (this.storageMode == 3) {
			// 		if(e[e.length-1]?.result){
			// 			if (e[e.length-1].result.code == 200) {
			// 				this.imgViewArr.push(e[e.length-1].result.data.url)
			// 				console.log(this.imgViewArr)
			// 				this.$refs.upload1.setItems(this.imgViewArr);
			// 				this.form.healthCertificate = this.imgViewArr.length === 1 ? this.imgViewArr[0].toString() : this.imgViewArr.join(',');
			// 			}
			// 		}

			// 	} else if (this.storageMode == 2) {
			// 		let url = this.alyOssSignatureInfo?.host + '/' + this.timeDate + this.suffix;
			// 		console.log(url)
			// 		// 上传一张就需要push进去  
			// 		this.imgViewArr.push(url)
			// 		this.$refs.upload1.setItems(this.imgViewArr);
			// 		this.form.healthCertificate = this.imgViewArr.length === 1 ? this.imgViewArr[0].toString() : this.imgViewArr.join(',');
			// 	}
			// },
			// 移除图片
			removeImg(e) {

				console.log(e)
				// const removeUrl = e.url

				// const findindex = this.imgViewArr.findIndex((item) => {
				// 	return item == removeUrl
				// })
				// this.imgViewArr.splice(findindex, 1)
				// this.$refs.upload1.setItems(this.imgViewArr);
			},

			async uploadHealthCertificateFn() {

				if (!this.imgStr.length) {
                   
					this.$sun.toast('请上传健康证书')
					return

				}
				
				console.log(this.form.healthCertificate)
				// 退出这个页面
				
				 if(this.technicianDetails.authenticationNot == 3){
					 console.log(this.technicianDetails)
					 this.formData = this.technicianDetails
					 const allForm={...this.formData,...this.form}
					 console.log(JSON.stringify(allForm) +'========================')
					 const saveRes = await this.$http.put({
					 	url: this.$api.technicianModifyIphone,
					 	data: {
					 		...allForm
					 	}
					 });
					 this.technicianDetail = allForm
					 console.log(saveRes.data+'======================')
					 this.technicianDetailsFn(this.technicianDetail ?this.technicianDetail:{})
					 
					 this.$sun.navBack();
				 }else{
					 this.uploadProgress({
					 	status: true,
					 	name: 'basicInformation'
					 })
					 
					 // console.log(this.form.healthCertificate)
					 this.uploadHealthCertificate(this.form.healthCertificate)
					 
					 this.$sun.navBack();
				 }

			}
		}
	}
</script>

<style lang="less">
	.uploadQualification {
		.text {
			margin-top: 30rpx;
			color: #999;
			text-align: left;
		}
		.htitle {
			color: black;
			font-weight: 700;
			font-size: 36rpx;
			text-align: left;

		}

		.sumbit-btn {
			width: 670rpx;
			position: fixed;

			bottom: 50rpx;

			height: 100rpx;
			color: #fff;
			border-radius: 10px;
			background-color: #1890FF;
		}

		/deep/ sunui-upimg {
			border: 3rpx dashed #D9D9D9;
		}
	}

	page {
		background-color: #ffff;
		text-align: center;
		padding: 40rpx;
	}
</style>